import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import { printRoutes } from "./utils/index";
import path from "path";
import { responseMiddleware } from "./middleware/response";
import { notFoundMiddleware } from "./middleware/404";
import { ErrorMiddleware } from "./middleware/error";
import { connectMongoDB } from "@/utils/db";
import session from "express-session";
import swaggerUi from "swagger-ui-express";
import swaggerDocument from "../apidoc.json";

// 加载.env和开发环境或生产环境环境变量
const NODE_ENV = process.env.NODE_ENV || "development"; // 默认为开发环境
dotenv.config({ path: ["../.env", `../.env.${NODE_ENV}`].map(p => path.resolve(__dirname, p)) });
import routes from "@/controllers/index"; // 内部要使用环境变量，要放在dotenv.config之后

const app = express();
const PORT = process.env.PORT ?? 8000;

app.use(
    session({
        secret: process.env.SESSIONSECRET!, // 服务器端生成session的签名
        name: "sessionCookie", // 修改session对应的cookie的名称
        resave: false, // 强制保存 session ，即使它并没有变化
        saveUninitialized: true, // 强制将未初始化的session存储
        cookie: {
            maxAge: 24 * 60 * 60 * 1000,
            secure: false, // true 表示只有https协议才能访问cookie
        },
        rolling: true, // 在每次请求时强行设置cookie，这将重置cookie的过期时间（默认值为false）
    })
);

app.use(cors({ origin: ["http://localhost:2003"], credentials: true }));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(`/`, responseMiddleware, routes);
app.use(process.env.API_BASE_URL!, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.use(notFoundMiddleware);
app.use(ErrorMiddleware);
app.listen(PORT, () => {
    console.log(`服务运行在http://localhost:${PORT}`);
    console.log(`文档运行在http://localhost:${PORT}${process.env.API_BASE_URL}`);
});
connectMongoDB();
printRoutes(app);

export default app;
